<?php

//会员主表模型
class MembersModel extends BaseModel {

    public $repassword;
    public $verifyCode;
    public $wangwang;
    public $agreement = 0;

    //返回表名
    public function tableName() {
        return '{{members}}';
    }

    public function rules() {
        return array(
            array('email', 'required', 'message' => '邮箱不能为空！'),
            array('email', 'unique', 'on' => 'create', 'message' => '您输入的邮件已被使用！<a href="' . Yii::app()->createUrl('/user/user/findpassword') . '">找回密码</a>'),
            array('username', 'unique', 'allowEmpty' => false, 'message' => '该用户名已经存在！'),
            array('email', 'email', 'message' => '您输入的邮件地址无效！'),
            array('password', 'length', 'tooShort' => '密码不能低于6位！', 'min' => 6),
            array('password', 'required', 'message' => '密码不能为空！'),
            array('repassword', 'compare', 'compareAttribute' => 'password', 'on' => 'create', 'message' => '两次输入密码不一致！'),
            array('verifyCode', 'captcha', 'on' => 'create'),
            array('agreement', 'in', 'on' => 'create', 'range' => array(1), 'message' => '您必须同意《用户注册协议》！'),
            array('group_id,experience,type,status,regip,regdate,lastloginip,lastlogintime,kind,sex, province,score,city,year,month,day,alipay,alipay_name,phone,is_lock,is_locklog', 'safe'),
        );
    }

    public function relations() {
        return array(
            'MembersMoneyModel' => array(self::HAS_ONE, 'MembersMoneyModel', 'uid'),
        );
    }

    public function attributeLabels() {
        return array(
            'uid' => 'Uid',
            'username' => 'Username',
            'group_id' => 'Group',
            'type' => '用户类型0为注册、1淘宝、2QQ、3SINA,q=%E8%BF%9E%E8%A1%A3%E8%A3%99',
            'password' => 'Password',
            'email' => 'Email',
            'status' => '是否激活',
            'regip' => 'Regip',
            'regdate' => 'Regdate',
            'lastloginip' => 'Lastloginip',
            'lastlogintime' => 'Lastlogintime',
            'kind' => '0shop1customer',
        );
    }

    //数据保存前置操作
    protected function beforeSave() {
        //更新会员组
        $groupInfo = MembersGroupModel::model()->getGroupList($this->group_id ? (int) $this->group_id : 1);
        if ($groupInfo['buffet_upgrade']) {
            $this->group_id = $this->getComputingPointGroupId($this->experience);
        }
        //邀请好友注册
        if ($this->status) {
            MembersInviteModel::model()->inviteActivate($this);
        }
        return true;
    }

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * 密码验证
     * @param type $password 明文密码
     * @return type
     */
    public function validatePassword($password) {
        return (md5($password) === $this->password) ? true : false;
    }

    /**
     * 根据明文密码，获取加密密码密文
     * @param string password 明文密码
     * @return string hash
     */
    public function hashPassword($password) {
        return md5($password);
    }

    /**
     * 删除会员
     * @param type $uid 用户uid 或者对象
     * @return boolean
     */
    public function deleteUser($uid) {
        if (empty($uid)) {
            return false;
        }
        if (is_object($uid)) {
            $model = $uid;
        } else {
            $model = $this->findByPk($uid);
        }
        if (empty($model) && !is_object($model)) {
            return false;
        }
        $userId = $model->uid;
        if ($model->delete()) {
            MembersInfoTaobaoModel::model()->deleteAll($this->where(array('uid' => $userId)));
            //删除绑定关系
            MembersOauthModel::model()->deleteBind($userId);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取用户基本表信息
     * @param type $identifier 用户名/用户UID
     * @return boolean
     */
    public function getUserInfo($identifier) {
        $where = array();
        //检测是否为uid登录方式
        if (is_int($identifier)) {
            $where['uid'] = (int) $identifier;
        } else {
            //判断登录方式
//            if (preg_match('/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/', $identifier)) {
//                $where['email'] = trim($identifier);
//            } else {
//                $where['username'] = trim($identifier);
//            }
            $where = " `email`='{$identifier}' or `username` = '{$identifier}' ";
        }
        if (empty($where)) {
            return false;
        }
        $model = $this->find($this->where($where));
        if (empty($model)) {
            return false;
        }
        return $model->attributes;
    }

    /**
     * 根据积分算出用户组
     * @param $experience int 成长值 
     */
    public function getComputingPointGroupId($experience = 0) {
        $groupid = 1;
        $grouppointlist = array();
        //获取会有组缓存
        $grouplist = MembersGroupModel::model()->getGroupList();
        foreach ($grouplist as $k => $v) {
            //只允许可以自助升级的会员组
            if ($v['buffet_upgrade']) {
                $grouppointlist[$k] = $v['experience'];
            }
        }
        //对数组进行逆向排序
        arsort($grouppointlist);
        //如果超出用户组积分设置则为积分最高的用户组
        if ($experience > max($grouppointlist)) {
            $groupid = key($grouppointlist);
        } else {
            foreach ($grouppointlist as $k => $v) {
                $tmp_k = $k;
                if ($experience >= $v) {
                    $groupid = $tmp_k;
                    break;
                }
            }
        }
        return $groupid;
    }

    /**
     * 增加成长值/经验值
     * @param type $uid 用户UID
     * @param type $exp 增加多少成长值
     * @param string $log 原因
     * @return boolean
     */
    public function plusExp($uid, $exp, $log = '') {
        $data = $this->findByPk((int) $uid);
        if (empty($data)) {
            return false;
        }
        $data->experience = $data->experience + (int) $exp;
        if ($data->validate() && $data->save()) {
            //增加日志
            if (empty($log)) {
                $log = date('Y-m-d H:i:s') . "增加经验值 {$exp}！";
            }
            return true;
        }
        return false;
    }

    /**
     * 增加积分，以后要加上版本控制，不然不够严谨
     * @param type $uid 用户ID
     * @param type $score 需要增加的积分
     * @param type $log 积分增加原因
     * @return boolean
     */
    public function plusScore($uid, $score, $log = '') {
        $data = $this->findByPk((int) $uid);
        if (empty($data)) {
            $this->addError('', '该用户不存在，无法增加积分！');
            return false;
        }
        $data->score = $data->score + (int) $score;
        if ($data->validate() && $data->save()) {
            //增加积分日志
            if (!empty($log)) {
                MembersActionModel::model()->addAction($uid, MembersActionModel::action_system, $log);
            }
            return true;
        }
        $this->addError('score', '积分增加失败！');
        return false;
    }

    /**
     * 积分扣除
     * @param type $uid 用户ID
     * @param type $score 需要扣除的积分数
     * @return boolean
     */
    public function deductionScore($uid, $score, $log = '') {
        $data = $this->findByPk((int) $uid);
        if (empty($data)) {
            $this->addError('score', '该用户积分为0，无法扣除积分！');
            return false;
        }
        if ($data->score - $score < 0) {
            $this->addError('score', '该用户积分不足，无法扣除积分！');
            return false;
        }
        $data->score = $data->score - (int) $score;
        if ($data->validate() && $data->save()) {
            //增加积分日志
            if (!empty($log)) {
                MembersActionModel::model()->addAction($uid, MembersActionModel::action_system, $log);
            }
            return true;
        }
        $this->addError('score', '扣除积分失败！');
        return false;
    }

    /**
     * 根据邮箱取得用户信息对象
     * @param type $email 用户邮箱
     * @return object
     */
    public function getMemberByEmail($email) {
        if (empty($email)) {
            return false;
        }
        $member = $this->find('email = ?', array($email));
        return $member;
    }

    /**
     * 判断手机号是号唯一
     * @return [type] [description]
     */
    public static function getByPhone($phone) {
        if ($phone) {
            return MembersModel::model()->find('phone = :phone', array('phone' => $phone));
        }
    }

}
